iT邦幫忙

0

跟著AI一起:從零打造一個互動式網站 Day23

wqq 2025-10-07 12:41:58142 瀏覽
  • 分享至 

  • xImage
  •  

LocalStorage 入門(儲存與讀取)

  1. 為什麼需要儲存資料?

在前端網頁開發裡,通常使用者輸入的資料在「重新整理網頁」後就會消失。
例如:

你在輸入框打了一段話,結果按下 F5 重新整理 → 內容不見了。

你選了網站的深色主題,下次回來又變成預設的淺色主題。

👉 這就是因為瀏覽器的記憶是「暫時」的。
為了改善這種情況,瀏覽器提供了 Web Storage API,讓開發者可以在使用者端儲存資料。

  1. LocalStorage 與 SessionStorage

LocalStorage = 長期記憶。
SessionStorage = 短期記憶。

  1. LocalStorage 的基本語法

LocalStorage 就像一個小型「資料庫」,只能存 文字 (string),不能直接存物件。

(1) 儲存資料

localStorage.setItem("username", "Sunny");
key = "username"
value = "Sunny"

(2) 讀取資料

let user = localStorage.getItem("username");
console.log(user); // Sunny

(3) 刪除資料
localStorage.removeItem("username");

(4) 清空所有資料
localStorage.clear();

  1. 如果要存物件怎麼辦?

因為 LocalStorage 只能存文字,所以要用 JSON 轉換:

// 物件
let userInfo = { name: "Sunny", age: 20 };

// 存入 (轉成字串)
localStorage.setItem("user", JSON.stringify(userInfo));

// 取出 (再轉回物件)
let data = JSON.parse(localStorage.getItem("user"));
console.log(data.name); // Sunny

👉 關鍵:JSON.stringify() 把物件變成字串存進去;
JSON.parse() 再轉回物件使用。

  1. 小專案:備忘錄
    HTML
<input type="text" id="memo" placeholder="輸入備忘錄">
<button id="save">儲存</button>
<div id="output"></div>

JavaScript

const input = document.getElementById("memo");
const btn = document.getElementById("save");
const output = document.getElementById("output");

// 預設載入之前的備忘錄
if (localStorage.getItem("note")) {
  output.innerText = localStorage.getItem("note");
}

btn.addEventListener("click", () => {
  const text = input.value;
  localStorage.setItem("note", text); // 存到 LocalStorage
  output.innerText = text; // 更新畫面
});

👉 功能說明:

使用者輸入文字後,按下「儲存」。
LocalStorage 會保存資料。
即使重新整理網頁,備忘錄還在。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言